//
//  QJOrderPayVC.m
//  QuanJieShopProject
//
//  Created by apple on 2018/2/23.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "QJOrderPayVC.h"
//支付宝SDK
#import <AlipaySDK/AlipaySDK.h>
//微信
#import "WXApiManager.h"
#import "PayMethodView.h"
@interface QJOrderPayVC () <WXApiManagerDelegate>

@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong)UITableView *tbView;
@property (nonatomic,assign)BOOL silverShow;//银元宝
@property (nonatomic,assign)BOOL yeShow;//余额
@property (nonatomic,assign)BOOL balanceShow;//积分
@property (nonatomic,assign)BOOL isYeEnough;//余额是否足够

@property (nonatomic,strong)PayMethodView *payView;
@end

@implementation QJOrderPayVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"支付";
    //支付宝支付成功通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayGengXingData) name:@"alipaysuccsed" object:nil];
    //支付宝支付失败通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayErrorAction) name:@"alipayerror" object:nil];
    //微信支付
    [WXApiManager sharedManager].delegate = self;
    [self createUI];
}

- (void)createUI{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, 150, 20)];
    label.text = @"请选择支付方式";
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = [UIColor lightGrayColor];
    [self.view addSubview:label];
    
    UILabel *moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(UISCREEN_WIDTH- 150, 20, 150, 20)];
    moneyLabel.text = [NSString stringWithFormat:@"总金额 %@ 元",self.totalAmountStr];
    moneyLabel.textColor = [UIColor redColor];
    moneyLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:moneyLabel];
    
    float y  =  CGRectGetMaxY(label.frame);
   
        y = 50+CGRectGetMaxY(label.frame);
        self.payView = [[PayMethodView alloc]init];
        self.payView.frame = CGRectMake(0, y, UISCREEN_WIDTH, 50);
        self.silverBtn = self.payView.selBtn;
        [self.silverBtn addTarget:self action:@selector(payMethodAcion:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.payView];
        
        [self.payView setViewWithImage:@"Hyuepay" title:@"银元宝积分" score:self.silverAmount];
        self.silverBtn.tag = 100;
   

        self.payView = [[PayMethodView alloc]init];
        self.payView.frame = CGRectMake(0, y+50, UISCREEN_WIDTH, 50);
        self.yeBtn = self.payView.selBtn;
        [self.yeBtn addTarget:self action:@selector(payMethodAcion:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.payView];
        [self.payView setViewWithImage:@"Hyuepay" title:@"余额" score:self.yeAmount];
        self.yeBtn.tag = 200;
   
    
    self.payView = [[PayMethodView alloc]init];
    self.payView.frame = CGRectMake(0, y+100, UISCREEN_WIDTH, 50);
    self.apayBtn = self.payView.selBtn;
    [self.apayBtn addTarget:self action:@selector(payMethodAcion:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.payView];
    [self.payView setViewWithImage:@"Hali" title:@"支付宝" score:@""];
    self.apayBtn.tag = 300;
    
    self.payView = [[PayMethodView alloc]init];
    self.payView.frame = CGRectMake(0, y+150, UISCREEN_WIDTH, 50);
    self.wxBtn = self.payView.selBtn;
    [self.wxBtn addTarget:self action:@selector(payMethodAcion:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.payView];
    [self.payView setViewWithImage:@"Hwx" title:@"微信" score:@""];
    self.wxBtn.tag = 400;
    
    UIButton *submitBtn = [UIButton buttonWithType:0];
    submitBtn.frame = CGRectMake(20, y+200+100, UISCREEN_WIDTH-40, 40);
    [submitBtn setBackgroundColor:[UIColor redColor]];
    [submitBtn setTitle:@"立即支付" forState:UIControlStateNormal];
    [submitBtn setTintColor:[UIColor whiteColor]];
    [submitBtn addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:submitBtn];
    
    
    UILabel *tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, y+350, UISCREEN_WIDTH-40, 100)];
    [self.view addSubview:tipLabel];
    tipLabel.numberOfLines = 0;
    tipLabel.text =@"温馨提示:可使用银元宝积分单独支付,银元宝积分不足时可使用会员积分单独支付,会员积分不足可使用会员积分+微信或支付宝混合支付.";
    tipLabel.textColor = [UIColor redColor];
    tipLabel.font = [UIFont systemFontOfSize:15];
    float total = [self.totalAmountStr intValue];
   
    float ye = [self.yeAmount intValue];
    
    if (ye<total) {
        self.isYeEnough = NO;
    }else{
        self.isYeEnough = YES;
    }
    
}
- (void)payMethodAcion:(UIButton *)button{
    button.selected = !button.selected;
    float total = [self.totalAmountStr intValue];
    float silver = [self.silverAmount intValue];
    float ye = [self.yeAmount intValue];
    if (ye>=total) {
        self.isYeEnough  = YES;
    }
    if (button.tag == 100) {//银元宝
       
        if (total>silver) {
            self.silverBtn.selected = NO;
            [MBPHUD showAlertWithTitle:@"银元宝不足,请使用其他支付方式"];
            return;
        }else{
            self.yeBtn.selected = NO;
            self.apayBtn.selected = NO;
            self.wxBtn.selected = NO;
        }
        
    }
    if (button.tag == 200) {//余额
        
        if (ye>=total) {
             self.silverBtn.selected = NO;
            self.apayBtn.selected = NO;
            self.wxBtn.selected = NO;
        }else{
            
            self.silverBtn.selected = NO;
        }
        
    }
    if (button.tag == 300) {//支付宝
        if (self.isYeEnough == YES) {
            if (self.yeBtn.selected == YES) {
                self.apayBtn.selected = NO;
                [MBPHUD showAlertWithTitle:@"余额可直接支付"];
                return;
            }
           
        }
        self.silverBtn.selected = NO;
        self.wxBtn.selected = NO;
        
    }
    if (button.tag == 400) {//微信
        if (self.isYeEnough == YES) {
            if (self.yeBtn.selected == YES) {
                self.wxBtn.selected = NO;
                [MBPHUD showAlertWithTitle:@"余额可直接支付"];
                return;
            }
            
        }
        self.silverBtn.selected =NO;
        self.apayBtn.selected = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    //控件不被导航栏遮挡
    self.navigationController.navigationBar.translucent = NO;
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //控件不被导航栏遮挡
    self.navigationController.navigationBar.translucent = YES;
}
#pragma mark -- 支付方法
- (void)payOrderActionWithPayStr:(id)payStr{
    
    if ([self.payType containsString:@"alipayapp"]) {
        
        NSString *responseStr = [NSString stringWithFormat:@"%@",payStr[@"data"]];
        //支付宝
        [[AlipaySDK defaultService] payOrder:responseStr fromScheme:MyAppScheme callback:^(NSDictionary *resultDic) {
            
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                //支付成功
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipaysuccsed" object:resultDic];
            }else{
                //支付失败
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipayerror" object:resultDic];
            }
            
        }];
    }else if ([self.payType containsString:@"appWeixinPay"]){
        //微信
        //时间戳
        //time_t now;
        //time(&now);
        //NSString *stamp  = [NSString stringWithFormat:@"%ld", now];
        if ([payStr isKindOfClass:[NSDictionary class]]) {
            PayReq *req = [[PayReq alloc]init];
            req.partnerId = [payStr objectForKey:@"partnerid"];
            req.prepayId = [payStr objectForKey:@"prepayid"];
            req.nonceStr = [payStr objectForKey:@"noncestr"];
            NSString *time = [payStr objectForKey:@"timestamp"];
            req.timeStamp = [time intValue];
            req.package = [payStr objectForKey:@"package"];
            req.sign = [payStr objectForKey:@"sign"];
            [WXApi sendReq:req];
        }
    }else{
        //余额
        [MBPHUD showAlertWithTitle:@"支付成功"];
        KPopViewControllerAction;
    }
}
#pragma mark -- 支付宝充值成功刷新数据
- (void)alipayGengXingData{
    
    [UIView animateWithDuration:3.0f animations:^{
        
        [MBPHUD showAlertWithTitle:@"支付宝支付成功!"];
        
    }completion:^(BOOL finished) {
        
        KPopViewControllerAction;
    }];
   
}
#pragma mark -- 支付宝充值失败的提示
- (void)alipayErrorAction{
    [UIView animateWithDuration:3.0f animations:^{
        
        [MBPHUD showAlertWithTitle:@"支付宝支付失败!"];
        
    }completion:^(BOOL finished) {
        
        KPopViewControllerAction;
    }];
}
#pragma mark -- 微信支付成功回调方法
- (void)managerDidPaySucced{
  
    [UIView animateWithDuration:3.0f animations:^{
        
        [MBPHUD showAlertWithTitle:@"微信支付成功!"];
        
    }completion:^(BOOL finished) {
        
        KPopViewControllerAction;
    }];
}
#pragma mark -- 微信支付失败回调方法
- (void)managerDidPayFailed{
    
    
    [UIView animateWithDuration:3.0f animations:^{
        
         [MBPHUD showAlertWithTitle:@"微信支付失败!"];
        
    }completion:^(BOOL finished) {
        
         KPopViewControllerAction;
    }];

}

- (void)submitAction:(UIButton *)button {
    
    if (self.silverBtn.selected == NO&&self.yeBtn.selected == NO&&self.apayBtn.selected ==NO&&self.wxBtn.selected == NO) {
        return;
    }
    if ([self.pay_code isEqualToString:@"appWeixinPay"]||[self.pay_code isEqualToString:@"alipayapp"]) {
    
        if (self.silverBtn.selected == YES) {
            self.silverBtn.selected = NO;
            [MBPHUD showAlertWithTitle:@"只能使用微信或支付宝支付"];
            return;
        }
        if (self.yeBtn.selected == YES) {
            self.yeBtn.selected  = NO;
             [MBPHUD showAlertWithTitle:@"只能使用微信或支付宝支付"];
            return;
        }
    }
    if (self.yeBtn.selected) {
        
        if (self.isYeEnough == NO) {
            
            if (self.apayBtn.selected == NO&&self.wxBtn.selected == NO) {
                
                [MBPHUD showAlertWithTitle:@"当前积分不足,可与微信或支付宝混合支付"];
                 return;
            }
           
        }
    }
    
    
    WEAKSELF
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.payOrderStr forKey:@"order_id"];
    if (self.silverBtn.selected == YES) {
        self.payType = @"balance";
        [dict setObject:self.totalAmountStr forKey:@"commit_silver_amount"];//银元宝ok
    }
    if (self.yeBtn.selected == YES) {
        
        if (self.isYeEnough) {
             [dict setObject:self.totalAmountStr forKey:@"commit_ye_amount"];//余额
        }else{
             [dict setObject:self.yeAmount forKey:@"commit_ye_amount"];//余额
        }
        if (self.apayBtn.selected == YES) {
            
            self.payType = @"alipayapp";
            
        }else if (self.wxBtn.selected == YES){
            
            self.payType = @"appWeixinPay";
            
        }else{
            
             self.payType = @"balance";
        }
    }
    if (self.yeBtn.selected  == NO&&self.silverBtn.selected == NO) {
        
        if (self.apayBtn.selected == YES) {
            
            self.payType = @"alipayapp";
            
        }
        
        if (self.wxBtn.selected == YES) {
            self.payType = @"appWeixinPay";
        }
    }
   
   [dict setObject:self.payType forKey:@"pay_code"];

    
    [WWNetRequest fetchPayOrderWithParameters:dict success:^(id response) {
        if (response) {
            
            [weakSelf payOrderActionWithPayStr:response];
        }
    } failure:^(NSDictionary *error) {
        
        [MBPHUD showAlertWithTitle:error[@"msg"]];
    }];
}


@end
